<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="goodForm" :rules="rules" ref="goodRef" label-width="100px" class="goodForm">

        <el-form-item required label="商品主图" prop="pictureUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadServer"
            accept="jpg,jpeg,png"
            :data= "{ bucketName: 'jiaolv',
                      moduleName: 'goods' }"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="goodForm.pictureUrl" :src="goodForm.pictureUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品名称" prop="name">
          <el-input style="width: 300px" v-model="goodForm.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="商品简介" prop="description">
          <el-input style="width: 300px" type="textarea" v-model="goodForm.description" placeholder="请输入商品简介(100字)"></el-input>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input type="number" min="0" style="width: 300px" v-model="goodForm.price" placeholder="请输入商品价格"></el-input>
        </el-form-item>

        <el-form-item label="商品库存" prop="stock">
          <el-input type="number" min="0" style="width: 300px" v-model="goodForm.stock" placeholder="请输入商品库存"></el-input>
        </el-form-item>

        <el-form-item label="上架状态" prop=" hasPublished">
          <el-radio-group v-model="goodForm. hasPublished">
            <el-radio :label=true>上架</el-radio>
            <el-radio :label=false>下架</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api/api'
export default {
  name: 'AddGood',
  setup() {
    const editor = ref(null)
    const goodRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    console.log(route.query)
    const goods = route.query
    const state = reactive({
      uploadServer: api.file.upload,
      id: goods.id || null,
      defaultCate: '',
      goodForm: {
        name: goods.name || '',
        description: goods.description || '',
        price: goods.price || '',
        stock: goods.stock || '',
        hasPublished: goods.hasPublished == 'true' ? true:false || false,
        pictureUrl: goods.pictureUrl || '',
      },
      rules: {
        name: [
          { required: 'true', message: '请填写商品名称', trigger: ['change'] }
        ],
        description: [
          {required: 'true', message: '请填写商品描述信息', trigger: ['change'] }
        ],
        price: [
          { required: 'true', message: '请填写商品价格', trigger: ['change'] }
        ],
        stock: [
          { required: 'true', message: '请填写商品库存', trigger: ['change'] }
        ],
        hasPublished: [
          { required: 'true', message: '请填写商品库存', trigger: ['change'] }
        ]
      },
    })
    const submitAdd = () => {
      goodRef.value.validate((vaild) => {
        if (vaild) {
          // 默认新增用 post 方法
          let params = {
            pictureUrl: state.goodForm.pictureUrl,
            description: state.goodForm.description,
            name: state.goodForm.name,
            hasPublished: state.goodForm.hasPublished,
            price: state.goodForm.price,
            stock: state.goodForm.stock,
          }
          let url
          if (state.id ) {
            params.id = state.id;
            params.createTime = goods.createTime;
            params.updateTime = goods.updateTime;
            params.isDeleted = goods.isDeleted;
            params.sales = goods.sales;
            url = api.goods.modify
          } else {
            url = api.goods.add
          }
          axios.post(url, params).then(() => {
            ElMessage.success(state.id ? '修改成功' : '添加成功')
            router.push({ path: '/goods' })
          })
        }
      })
    }
    const handleBeforeUpload = (file) => {
      const isJPG = ['image/jpg', 'image/jpeg', 'image/png'].includes(file.type) ;

      const isLt2M = file.size / 1024 / 1024 < 10;

      if ( !isJPG ) {
        ElMessage.error('上传头像图片只能是 jpg、jpeg、png 格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    }
    const handleUrlSuccess = (val) => {
      state.goodForm.pictureUrl = val.data || ''
    }
    return {
      ...toRefs(state),
      goodRef,
      submitAdd,
      handleBeforeUpload,
      handleUrlSuccess,
      editor,
    }
  }
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
</style>